import 'package:base_plugin/base_plugin.dart';
import 'package:dio/dio.dart';
import 'package:finance_app/src/entities/data_report_entity.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

mixin ReportRefreshMixin on BaseProvider<DataReportEntity> {
  RefreshController refreshController = RefreshController();

  int get initPage => 1;

  int get initRows => 15;
  int page;
  int rows;
  bool hasUp = false;

  DataReportEntity get reportData;

  Future get refreshFuture;

  @override
  void initState() {
    page = initPage;
    rows = initRows;
    super.initState();
  }

  bool get canRefreshFuture => true;

  Future<void> onRefresh() async {
    page = initPage;
    if (canRefreshFuture)
      await post(refreshFuture, onSuccess: (result) {
        final data = getFromRequestResult(result, true);

        hasUp = data.body.length >= rows;

        addData(data, true);
        update();
      }, autoHandler: AutoHandler.Toast);
    refreshController.refreshCompleted();
  }

  void addData(DataReportEntity data, bool isRefresh) {
    DataReportEntity oldDataList = reportData;
    if (isRefresh) {
      oldDataList.body.clear();
    }
    oldDataList.body.addAll(data.body);
  }

  void onLoadMore() async {
    page++;
    await post(refreshFuture,
        onSuccess: (result) {
          final data = getFromRequestResult(result, false);
          hasUp = data.body.length >= rows;
          addData(data, false);
          update();
        },
        autoHandler: AutoHandler.Toast,
        onError:
            (int statusCode, String msg, Object error, StackTrace stackTrace) {
          page--;
        });
    refreshController.loadComplete();
  }

  DataReportEntity getFromRequestResult(Response result, bool isRefresh);
}
